<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH . 'controllers/main.php';

/**
 * Контроллер каталога видео
 *
 * @package CoreFramework
 * @version 1.0
 * @author Gennadiy Kozlenko
 */
class Catalog extends Main {

   /**
    * Номер страницы
    *
    * @access private
    * @var integer
    */
   var $_page = 1;

   /**
    * Количество результатов на страницу
    *
    * @access private
    * @var integer
    */
   var $_per_page = 6;

   /**
    * Фильтр по жанру
    *
    * @var int
    */
   var $_id_genre = 0;

   /**
    * Фильтр по стране
    *
    * @var int
    */
   var $_id_country = 0;

   /**
    * Фильтр по актеру
    *
    * @var int
    */
   var $_id_actor = 0;

   /**
    * Фильтр по режиссеру
    *
    * @var int
    */
   var $_id_director = 0;

   /**
    * Фильтр по году
    *
    * @var int
    */
   var $_year = 0;

   /**
    * Фильтр по новинкам
    *
    * @var bool
    */
   var $_is_novelty = false;

   /**
    * Массив найденых результатов
    *
    * @access private
    * @var array
    */
   var $_results = array();

   /**
    * Общее количество результатов
    *
    * @access private
    * @var integer
    */
   var $_all_count = 0;

   /**
    * Конструктор класса
    *
    * @access public
    * @return Catalog
    */
   function Catalog() {
      parent::Main();
      if (false !== $this->input->get('page')) {
         $this->_page = (int) $this->input->get('page');
         $this->_page = 1 < $this->_page ? $this->_page : 1;
      }
      $this->_per_page = $this->variables->get('catalog_per_page', $this->_per_page);
      $this->set_layout('video');
   } // end Catalog

   /**
    * Метод по умолчанию
    *
    * @access public
    */
   function index() {
      // Подгружаем результаты
      $this->_load_results();

      $pagination = '';
      $pages = ceil($this->_all_count / $this->_per_page);
      if ($this->_all_count > count($this->_results)) {
         $this->load->helper('link');
         $this->load->library('pagination');
         $this->pagination->set_page($this->_page);
         $this->pagination->set_num_pages($pages);
         $this->pagination->set_url(create_link($this->get_controller(), $this->get_method(), array('page' => '{%page%}')));
         $pagination = $this->pagination->create_links();
      }

      $data = array(
              'show_path'   => array(),
              'results'     => $this->_results,
              'pagination'  => $pagination,
              'prev_page'   => 1 < $this->_page ? create_link($this->get_controller(), $this->get_method(), array('page' => $this->_page - 1)) : create_link($this->get_controller(), $this->get_method(), array('page' => $this->_page)),
              'next_page'   => $pages > $this->_page ? create_link($this->get_controller(), $this->get_method(), array('page' => $this->_page + 1)) : create_link($this->get_controller(), $this->get_method(), array('page' => $this->_page))
      );
      $data['no_results'] = empty($data['results']) ? array(array()) : array();

      $this->set_content($this->parser->parse('video/catalog.html', $data, true));
      $this->display();
   } // end index

   /**
    * Метод с поиском по жанру
    *
    * @param string $slug
    * @access public
    */
   function genre($slug) {
      // Подгружаем нужный жанр
      $this->load->model('m_genre');
      $this->_id_genre = $this->m_genre->get_id_by_slug($slug);
      if (0 == $this->_id_genre) {
         // Редирект на основной каталог
         $this->redirect($this->get_controller());
      }
      $this->m_genre->set_id($this->_id_genre);

      // Подгружаем результаты
      $this->_load_results();

      // Получаем title
      $title = $this->m_genre->get('title');

      // Pagination
      $pagination = '';
      $pages = ceil($this->_all_count / $this->_per_page);
      if ($this->_all_count > count($this->_results)) {
         $this->load->helper('link');
         $this->load->library('pagination');
         $this->pagination->set_page($this->_page);
         $this->pagination->set_num_pages($pages);
         $this->pagination->set_url(create_link('genre', $slug, array('page' => '{%page%}')));
         $pagination = $this->pagination->create_links();
      }

      // Output
      $data = array(
              'results'     => $this->_results,
              'pagination'  => $pagination,
              'prev_page'   => 1 < $this->_page ? create_link('genre', $slug, array('page' => $this->_page - 1)) : create_link('genre', $slug, array('page' => $this->_page)),
              'next_page'   => $pages > $this->_page ? create_link('genre', $slug, array('page' => $this->_page + 1)) : create_link('genre', $slug, array('page' => $this->_page))
      );
      $data['no_results'] = empty($data['results']) ? array(array()) : array();

      $this->set_metadata('catalog_by_genre', $title);
      $this->set_content($this->parser->parse('video/catalog.html', $data, true));
      $this->display();
   } // end index

   /**
    * Метод с поиском по стране
    *
    * @param string $slug
    * @access public
    */
   function country($slug) {
      // Подгружаем нужную страну
      $this->load->model('m_country');
      $this->_id_country = $this->m_country->get_id_by_slug($slug);
      if (0 == $this->_id_country) {
         // Редирект на основной каталог
         $this->redirect($this->get_controller());
      }
      $this->m_country->set_id($this->_id_country);

      // Подгружаем результаты
      $this->_load_results();

      // Pagination
      $pagination = '';
      $pages = ceil($this->_all_count / $this->_per_page);
      if ($this->_all_count > count($this->_results)) {
         $this->load->helper('link');
         $this->load->library('pagination');
         $this->pagination->set_page($this->_page);
         $this->pagination->set_num_pages($pages);
         $this->pagination->set_url(create_link('country', $slug, array('page' => '{%page%}')));
         $pagination = $this->pagination->create_links();
      }

      // Output
      $data = array(
              'results'     => $this->_results,
              'pagination'  => $pagination,
              'prev_page'   => 1 < $this->_page ? create_link('country', $slug, array('page' => $this->_page - 1)) : create_link('country', $slug, array('page' => $this->_page)),
              'next_page'   => $pages > $this->_page ? create_link('country', $slug, array('page' => $this->_page + 1)) : create_link('country', $slug, array('page' => $this->_page))
      );
      $data['no_results'] = empty($data['results']) ? array(array()) : array();

      $this->set_metadata('catalog_by_country', $this->m_country->get('title'));
      $this->set_content($this->parser->parse('video/catalog.html', $data, true));
      $this->display();
   } // end index

   /**
    * Метод с поиском по актеру
    *
    * @param string $slug
    * @access public
    */
   function actor($slug) {
      // Подгружаем нужную персону
      $this->load->model('m_person');
      $this->_id_actor = $this->m_person->get_id_by_slug($slug);
      if (0 == $this->_id_actor) {
         // Редирект на основной каталог
         $this->redirect($this->get_controller());
      }
      $this->m_person->set_id($this->_id_actor);

      // Подгружаем результаты
      $this->_load_results();

      // Pagination
      $pagination = '';
      $pages = ceil($this->_all_count / $this->_per_page);
      if ($this->_all_count > count($this->_results)) {
         $this->load->helper('link');
         $this->load->library('pagination');
         $this->pagination->set_page($this->_page);
         $this->pagination->set_num_pages($pages);
         $this->pagination->set_url(create_link('actor', $slug, array('page' => '{%page%}')));
         $pagination = $this->pagination->create_links();
      }

      // Output
      $data = array(
              'results'     => $this->_results,
			  'description' => $this->m_person->get('description'),
              'pagination'  => $pagination,
              'prev_page'   => 1 < $this->_page ? create_link('actor', $slug, array('page' => $this->_page - 1)) : create_link('actor', $slug, array('page' => $this->_page)),
              'next_page'   => $pages > $this->_page ? create_link('actor', $slug, array('page' => $this->_page + 1)) : create_link('actor', $slug, array('page' => $this->_page))
      );
      $data['no_results'] = empty($data['results']) ? array(array()) : array();

      $this->set_metadata('catalog_by_actor', $this->m_person->get('title'));
      $this->set_content($this->parser->parse('video/catalog.html', $data, true));
      $this->display();
   } // end index

   /**
    * Метод с поиском по директору
    *
    * @param string $slug
    * @access public
    */
   function director($slug) {
      // Подгружаем нужную персону
      $this->load->model('m_person');
      $this->_id_director = $this->m_person->get_id_by_slug($slug);
      if (0 == $this->_id_director) {
         // Редирект на основной каталог
         $this->redirect($this->get_controller());
      }
      $this->m_person->set_id($this->_id_director);

      // Подгружаем результаты
      $this->_load_results();

      // Pagination
      $pagination = '';
      $pages = ceil($this->_all_count / $this->_per_page);
      if ($this->_all_count > count($this->_results)) {
         $this->load->helper('link');
         $this->load->library('pagination');
         $this->pagination->set_page($this->_page);
         $this->pagination->set_num_pages($pages);
         $this->pagination->set_url(create_link('director', $slug, array('page' => '{%page%}')));
         $pagination = $this->pagination->create_links();
      }

      // Output
      $data = array(
              'results'     => $this->_results,
              'pagination'  => $pagination,
              'prev_page'   => 1 < $this->_page ? create_link('director', $slug, array('page' => $this->_page - 1)) : create_link('director', $slug, array('page' => $this->_page)),
              'next_page'   => $pages > $this->_page ? create_link('director', $slug, array('page' => $this->_page + 1)) : create_link('director', $slug, array('page' => $this->_page))
      );
      $data['no_results'] = empty($data['results']) ? array(array()) : array();

      $this->set_metadata('catalog_by_director', $this->m_person->get('title'));
      $this->set_content($this->parser->parse('video/catalog.html', $data, true));
      $this->display();
   } // end index

   /**
    * Метод с поиском по году
    *
    * @param string $slug
    * @access public
    */
   function year($year) {
      $this->_year = $year;
      // Подгружаем результаты
      $this->_load_results();

      // Pagination
      $pagination = '';
      $pages = ceil($this->_all_count / $this->_per_page);
      if ($this->_all_count > count($this->_results)) {
         $this->load->helper('link');
         $this->load->library('pagination');
         $this->pagination->set_page($this->_page);
         $this->pagination->set_num_pages($pages);
         $this->pagination->set_url(create_link('year', $year, array('page' => '{%page%}')));
         $pagination = $this->pagination->create_links();
      }

      // Output
      $data = array(
              'results'     => $this->_results,
              'pagination'  => $pagination,
              'prev_page'   => 1 < $this->_page ? create_link('year', $year, array('page' => $this->_page - 1)) : create_link('year', $year, array('page' => $this->_page)),
              'next_page'   => $pages > $this->_page ? create_link('year', $year, array('page' => $this->_page + 1)) : create_link('year', $year, array('page' => $this->_page))
      );
      $data['no_results'] = empty($data['results']) ? array(array()) : array();

      $this->set_metadata('catalog_by_year', $year);
      $this->set_content($this->parser->parse('video/catalog.html', $data, true));
      $this->display();
   } // end index

   /**
    * Отображение только новинок кино
    *
    * @access public
    */
   function novelty() {
      // Показывать только новинки кино
      $this->_is_novelty = true;

      // Подгружаем результаты
      $this->_load_results();

      // Pagination
      $pagination = '';
      $pages = ceil($this->_all_count / $this->_per_page);
      if ($this->_all_count > count($this->_results)) {
         $this->load->helper('link');
         $this->load->library('pagination');
         $this->pagination->set_page($this->_page);
         $this->pagination->set_num_pages($pages);
         $this->pagination->set_url(create_link('novelty', 'index', array('page' => '{%page%}')));
         $pagination = $this->pagination->create_links();
      }

      // Output
      $data = array(
              'results'     => $this->_results,
              'pagination'  => $pagination,
              'prev_page'   => 1 < $this->_page ? create_link('novelty', 'index', array('page' => $this->_page - 1)) : create_link('novelty', 'index', array('page' => $this->_page)),
              'next_page'   => $pages > $this->_page ? create_link('novelty', 'index', array('page' => $this->_page + 1)) : create_link('novelty', 'index', array('page' => $this->_page))
      );
      $data['no_results'] = empty($data['results']) ? array(array()) : array();

      $year = date('Y');
      if (3 >= date('m')) {
         $year = date('Y') - 1;
      }

      $this->set_metadata('catalog_by_novelty', $year);
      $this->set_content($this->parser->parse('video/catalog.html', $data, true));
      $this->display();
   } // end index

   /**
    * Процесс поиска
    *
    * @access private
    */
   function _load_results() {
      $this->load->helper('content');

      $this->benchmark->mark('load_catalog_start');

      $this->_results = array();
      $this->_all_count = 0;
      $this->load->helper('thumbnail');

      // Получаем остальные видео
      $this->db->select('SQL_CALC_FOUND_ROWS v.id_video, v.title, v.description, v.image, v.year, ROUND(TIME_TO_SEC(v.length) / 60) AS minutes', false)
              ->select('v.num_downloaded, "no" AS is_featured, IF(v.num_ratings > 0, v.sum_ratings / v.num_ratings, 0) AS rating', false)
              ->select('(SELECT COUNT(*) FROM ' . $this->db->dbprefix('video_comments') . ' vcom WHERE v.id_video = vcom.id_video) AS comments', false)
              ->from('videos v')
              ->where('v.status', 'active')
              ->where('v.num_torrents >', 0)
              ->where('v.year <=', date('Y'));
      if (0 < $this->_id_genre) {
         $this->db->join('video_genres vg', 'v.id_video = vg.id_video')
                 ->where('vg.id_genre', $this->_id_genre);
      }
      if (0 < $this->_id_country) {
         $this->db->join('video_countries vc', 'v.id_video = vc.id_video')
                 ->where('vc.id_country', $this->_id_country);
      }
      if (0 < $this->_id_actor) {
         $this->db->join('video_actors va', 'v.id_video = va.id_video')
                 ->where('va.id_person', $this->_id_actor);
      }
      if (0 < $this->_id_director) {
         $this->db->join('video_directors vd', 'v.id_video = vd.id_video')
                 ->where('vd.id_person', $this->_id_director);
      }
      if (0 < $this->_year) {
         $this->db->where('v.year', $this->_year);
      }
      if ($this->_is_novelty) {
         $this->db->where('v.year >=', $this->_get_novelty_year());
         $this->db->order_by('v.year', 'desc');
      }
      $this->db->group_by('v.id_video')
              ->order_by('v.date_created', 'desc')
              ->limit($this->_per_page - count($this->_results), ($this->_page - 1) * $this->_per_page);
      $query = $this->db->get();
      if (0 < $query->num_rows()) {
         $this->_results = array_merge($this->_results, $query->result_array());
         $query = $this->db->query("SELECT FOUND_ROWS() AS rows");
         if (0 < $query->num_rows()) {
            $row = $query->row_array();
            $this->_all_count = $row['rows'];
         }
      }

      foreach ($this->_results as &$row) {
         if (empty($row['image'])) {
            $row['image'] = base_url() . 'images/no_image.jpg';
         } else {
            $row['image'] = base_url() . create_thumbnail($row['image'], 100, 150);
         }
         $row['uid'] = md5(uniqid());
         $row['description'] = get_abstract(stripslashes($row['description']), 200);
      }
      unset($row);
      $this->benchmark->mark('load_catalog_end');
   } // end _load_results

   /**
    * Получение года для нокинок кино
    *
    * @return int
    */
   function _get_novelty_year() {
      $year = date('Y') - 1;
      return $year;
   }

}
